package com.tarena.tp.luban.worker.admin.manager;

import com.tarena.tp.luban.account.server.client.AccountApi;
import com.tarena.tp.luban.account.server.param.AccountParam;
import com.tarena.tp.luban.worker.admin.bo.AuditBO;
import com.tarena.tp.luban.worker.admin.bo.WorkerBO;
import com.tarena.tp.luban.worker.admin.protocol.param.AuditParam;
import com.tarena.tp.luban.worker.admin.protocol.param.WorkerParam;
import com.tarena.tp.luban.worker.admin.repository.AuditLogRepository;
import com.tarena.tp.luban.worker.admin.repository.WorkerRepository;
import com.tarena.tp.luban.worker.server.common.enums.AccountStatusEnum;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;

import java.util.List;

@Slf4j
@Service
public class AuditService {

    @Autowired
    private AuditLogRepository auditLogRepository;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private AccountApi accountApi;

    /**
     * 新增审核
     */
    public Long saveAudit(AuditParam auditParam) throws BusinessException {
        WorkerParam workerParam = new WorkerParam();
        Long workerId = auditParam.getWorkerId();
        workerParam.setUserId(auditParam.getWorkerId());
        workerParam.setAuditStatus(auditParam.getAuditStatus());
        workerService.updateAuditStatus(workerParam);
        Long result = this.auditLogRepository.save(auditParam);
        WorkerBO worker = workerService.getWorker(workerId);
        if (worker != null && AccountStatusEnum.DISABLE.getValue().equals(worker.getCertStatus())) {
            //创建账户
            Long account = createAccount(workerId, worker.getRealName(), worker.getPhone());
            if (account > 0) {
                workerParam.setCertStatus(AccountStatusEnum.ENABLE.getValue());
                workerService.updateCertStatus(workerParam);
                log.info("create account success,req:{},resp:{}",workerId,account);
            }else {
                log.error("create account failed,req:{},resp:{}",workerId,account);
            }
        }
        return result;
    }

    private Long createAccount(Long userId,String userName,String userPhone){
        AccountParam accountParam = new AccountParam();
        accountParam.setUserId(userId);
        accountParam.setUserName(userName);
        accountParam.setUserPhone(userPhone);
        return accountApi.create(accountParam);
    }

    /**
     * 审核详情
     */
    public WorkerBO getAudit(Long workerId) throws BusinessException{
        WorkerBO worker = workerService.getWorker(workerId);
        if (worker != null) {
            List<AuditBO> audit = auditLogRepository.getAudit(workerId);
            worker.setWorkerAuditLogs(audit);
        }
        return worker;
    }
}
